<template>
  <el-select v-model="modelValue" placeholder="Select" :show-arrow="false" :loading="loading" :offset="3" filterable style="width: 100%">
    <el-option v-for="(item, index) in optionList" :key="index" :label="item[props.textField]" :value="item[props.valueField]"> </el-option>
    <template #footer>
      <div style="width: 100%; display: flex; justify-content: end" v-if="!isAdding">
        <el-button size="small" type="primary" @click="onAddOption"> 新增 </el-button>
        <el-button size="small" @click="onReload"> 刷新 </el-button>
      </div>
      <template v-else>
        <div style="height: 300px; width: 100%"></div>
        <el-input v-model="optionName" class="option-input" placeholder="输入选项名称" size="small" />
        <div style="width: 100%; display: flex; justify-content: end">
          <el-button type="primary" size="small" @click="onConfirm"> 确认 </el-button>
          <el-button size="small" @click="clear">取消</el-button>
        </div>
      </template>
    </template>
  </el-select>
</template>
<script setup lang="ts" generic="T extends IMasterEntity">
import type { IMasterEntity } from '@/types/entity';
import { dwHttp } from '@/utils/http';
import { onMounted, ref, watch } from 'vue';
defineOptions({
  name: 'DropdownSelector',
});
const props = defineProps({
  url: {
    type: String,
    required: true,
  },
  textField: {
    type: String,
    default: () => {
      return 'name';
    },
  },
  valueField: {
    type: String,
    default: () => {
      return 'id';
    },
  },
  params: {
    type: Object,
  },
});
const url: string = props.url;
const params: object = props.params || {};
const loading = ref(false);
const isAdding = ref(false);
const modelValue = defineModel();
const optionName = ref('');
const optionList = ref<Record<string, string>[]>([]);
const onAddOption = () => {
  isAdding.value = true;
};
const onConfirm = () => {
  if (optionName.value) {
    clear();
  }
};
const clear = () => {
  optionName.value = '';
  isAdding.value = false;
};
const loadData = () => {
  dwHttp({
    url: url,
    params: params,
    isSuccessTip: false,
  }).then((res) => {
    optionList.value = res.data as unknown as Record<string, string>[];
  });
};

const onReload = () => {};

onMounted(() => {
  loadData();
});
</script>
<style lang="scss" scoped>
.option-input {
  width: 100%;
  margin-bottom: 8px;
}
</style>
